import cloud from '@lafjs/cloud'
let dbName = "web-order"
const db = cloud.mongo.db

export default async function (ctx: FunctionContext) {
  let data = ctx.body

  let obj = {}
  if (data.year) {
    let arr = []

    //传入年份的start和end内
    const startOfYear = new Date(data.year, 0, 1).getTime(); // 该年份的开始时间戳
    const endOfYear = new Date(data.year, 11, 31, 23, 59, 59, 999).getTime(); // 该年份的结束时间戳

    //判断是否有挪至次年的标记，有的话是否等于传入的年份
    let aa = await db.collection(dbName).find({
      statisticsYear: {
        $exists: true,   // 判断属性存在[1,2](@ref)
        $eq: data.year        // 验证值等于2025[5](@ref)
      }
    }).project({ _id: 1 }).toArray()

    //没有标记，正常筛选
    let timeobj = {
      _add_time: { $gte: startOfYear, $lt: endOfYear },
      statisticsYear: { $exists: false }
    }
    let bb = await db.collection(dbName).find(timeobj).project({ _id: 1 }).toArray()

    let cc = [...aa, ...bb]
    cc.forEach(element => {
      arr.push(element._id)
    });

    obj["_id"] = { $in: arr } //特定的订单id
  }

  if (data.status && data.status.length) {
    let statusList = [...data.status]
    //如果有报名成功的状态，则添加到10状态
    if (statusList.includes(2) && !statusList.includes(10)) statusList.push(10)
    obj["status"] = { $in: statusList }
  } else {
    obj["status"] = { $in: [2, 7, 10] }
  }

  if (data.curriculum_id && data.curriculum_id.length) obj['curriculum_id'] = { $in: data.curriculum_id }

  let fieldJson = { curriculum_id: 1, displayPrice: 1, status: 1 }

  let curriculums = await db.collection("web-course").find({}).project({ _id: 1, name: 1 }).toArray()
  let aa = await db.collection(dbName).find(obj).project(fieldJson).toArray()

  let bb = summarizeCourseOrders(aa)
  bb.forEach(element => {
    let index = cloud.utils.findIndexByField(curriculums, "_id", element.curriculum_id)
    element.name = curriculums[index].name
  });

  return cloud.utils.requestReturn({ data: bb })
}


/**
 * 统计课程订单数据，按课程ID和状态分组计算订单数量和总金额
 * @param {Array} orders - 订单数组，包含curriculum_id、status和displayPrice字段
 * @returns {Array} 分组统计结果数组
 */
function summarizeCourseOrders(orders) {
  // 使用reduce方法进行分组统计
  const summaryResult = orders.reduce((accumulator, currentOrder, currentIndex) => {
    // 创建分组键，结合课程ID和状态
    const groupKey = `${currentOrder.curriculum_id}-${currentOrder.status}`;

    // 如果该分组不存在，初始化分组数据
    if (!accumulator[groupKey]) {
      accumulator[groupKey] = {
        curriculum_id: currentOrder.curriculum_id,
        status: currentOrder.status,
        count: 0,
        totalAmount: 0,
        // 记录该curriculum_id第一次出现的顺序
        firstOccurrenceIndex: currentIndex
      };
    }

    // 更新分组统计：订单数量+1，累计金额
    accumulator[groupKey].count += 1;
    accumulator[groupKey].totalAmount += currentOrder.displayPrice;

    return accumulator;
  }, {}); // 初始值为空对象

  // 将分组结果对象转换为数组
  const resultArray = Object.values(summaryResult);

  // 按curriculum_id分组，并保持原始顺序
  const groupedByCurriculum = resultArray.reduce((groups, item) => {
    const curriculumId = item.curriculum_id;
    if (!groups[curriculumId]) {
      groups[curriculumId] = [];
    }
    groups[curriculumId].push(item);
    return groups;
  }, {});

  // 按照curriculum_id第一次出现的顺序排序，然后扁平化数组
  const sortedResult = [];
  const seenCurriculumIds = new Set();

  // 按照原始顺序遍历，确保curriculum_id的顺序不变
  resultArray.forEach(item => {
    if (!seenCurriculumIds.has(item.curriculum_id)) {
      seenCurriculumIds.add(item.curriculum_id);
      // 将该curriculum_id的所有分组按状态顺序加入结果
      if (groupedByCurriculum[item.curriculum_id]) {
        // 如果需要按status排序，可以在这里添加排序逻辑
        sortedResult.push(...groupedByCurriculum[item.curriculum_id]);
      }
    }
  });

  // 移除临时添加的firstOccurrenceIndex属性
  return sortedResult.map(({ firstOccurrenceIndex, ...item }) => item);
}